package com.neuedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neuedu.config.NeueduException;
import com.neuedu.entity.UmsUser;
import com.neuedu.mapper.UmsUserMapper;
import com.neuedu.service.SysFileService;
import com.neuedu.service.UmsUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.util.JwtUtil;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 王禹
 * @since 2025-08-07
 */
@Service
public class UmsUserServiceImpl extends ServiceImpl<UmsUserMapper, UmsUser> implements UmsUserService {

    @Resource
    PasswordEncoder passwordEncoder;
    @Resource(name = "wyRedisTemplate")
    RedisTemplate<String, Object> redisTemplate;
    @Resource
    SysFileService sysFileService;
    @Override
    public boolean check(String field, String value, Long id) {
        QueryWrapper<UmsUser> wrapper = new QueryWrapper<>();
        wrapper.eq(field, value);
        if (null != id) {
            wrapper.ne("id", id);
        }
        return this.count(wrapper) == 0;
    }

    @Override
    public boolean add(UmsUser umsUser, MultipartFile file, String password) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        umsUser.setPassword(passwordEncoder.encode(password));
        umsUser.setIcon(sysFileService.upload(file, "icon"));
        return this.save(umsUser);
    }

    @Override
    @Deprecated
    public String login(String username, String password) {
        QueryWrapper<UmsUser> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", username)
                .or().eq("email", username);
        UmsUser umsUser = this.getOne(wrapper);
        if (null == umsUser || !passwordEncoder.matches(password, umsUser.getPassword())) {
            throw new NeueduException("用户或密码错误");
        }
        if(!umsUser.getActive()) {
            throw new NeueduException("该用户已经禁用，无法登录");
        }
        String key = String.format("ums:%d:login", umsUser.getId());
        redisTemplate.opsForValue().set(key, umsUser, 30, TimeUnit.MINUTES);
        return "null";
    }

}
